﻿using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.ComponentModel;

namespace StarsAdmin.Web.Core.Filter
{
    /// <summary>
    /// 设置swagger参数默认值显示过滤器
    /// </summary>
    public class DefaultValueOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            foreach (var parameter in operation.Parameters)
            {
                var paramName = parameter.Name;
                var paramInfo = context.MethodInfo.GetParameters().FirstOrDefault(p => p.Name == paramName);

                if (paramInfo != null && paramInfo.CustomAttributes.Any(attr => attr.AttributeType == typeof(DefaultValueAttribute)))
                {
                    var defaultValueAttr = paramInfo.CustomAttributes.First(attr => attr.AttributeType == typeof(DefaultValueAttribute));
                    var defaultValue = defaultValueAttr.NamedArguments.FirstOrDefault(arg => arg.MemberName == nameof(DefaultValueAttribute.Value)).TypedValue.Value;

                    // 添加自定义扩展字段
                    parameter.Extensions.Add("x-default", new OpenApiString(defaultValue.ToString()));
                }
            }
        }
    }
}